
   var oppFormIds = ["opportunityTitle","dealSize","oppClosingProbability","salesPerson","stage",
	                  "createDate","status","targetDate","actualCloseDate","opportunityDiscription"];
   
   var oppValidationFormIds = ["opportunityTitle","dealSize","oppClosingProbability","salesPerson","stage",
	                  "createDate","status","targetDate","actualCloseDate","opportunityDiscription","firstName","companyName"];


function createOpportunityPanel(){
	
		var opportunityStore = CRM.commons.createStore('opportunityStoreid',CRM.SPComp.opportunityDataArray,'searchopportunities/showOpportunities');
		var oppSearchCriteriaStore = CRM.commons.createComboStore('searchCriteriaid','searchopportunities/oppSearchTypes','');
		
		var confidencelevelStore = CRM.commons.createComboStore('confidencelevelStoreid','opportunity/opportunityReqCombo','confidencelevelTypes');
		var stageStore = CRM.commons.createComboStore('stageStoreid','opportunity/opportunityReqCombo','stageTypes');
		var statusStore = CRM.commons.createComboStore('statusStoreid','opportunity/opportunityReqCombo','statusTypes');
		
		var salespersonStore = CRM.commons.createComboStore('salespersonStoreid','opportunity/salespersonTypes','');
		
		//var leadStore=CRM.commons.createStore('leadStoreid',CRM.SPComp.leadDataArray,'searchleads/showLeads'); This line of code has be moved to showLeadSearchWindow.  
        //var leadSearchCriteriaStore=CRM.commons.createComboStore('leadSearchCriteriaStoreid', 'opportunity/leadSearchCriteriaTypes');


        //Date Validation
        Ext.apply(Ext.form.VTypes, {
		daterange : function(val, field) {
			var date = field.parseDate(val);
	 
			if(!date){
				return;
			}
			if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
				var start = Ext.getCmp(field.startDateField);
				start.setMaxValue(date);
				start.validate();
				this.dateRangeMax = date;
			} 
			else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
				var end = Ext.getCmp(field.endDateField);
				end.setMinValue(date);
				end.validate();
				this.dateRangeMin = date;
			}
			return true;
		}
	});
        	
        var opportunityPanel = {
                    xtype       : 'fieldset',
                    id          : 'opportunityPanel',
                    title       : 'Opportunity Information',
                    width       : 520,
                    height      : 300,
                    layout      : 'form',
                    labelWidth  : 140,
                    items       : [
									{ 
									    xtype     : 'hidden',
									    id        : 'opportunityId',
									    fieldLabel: 'Opportunity Id'
									},
                                    {
                                      xtype      : 'textfield',
                                      fieldLabel : 'Opportunity Title<font color=red>*</font>',
                                      id         : 'opportunityTitle',
                                      //name       : 'opportunityTitle',
                                      width      : 330
                                      //allowBlank : false
                                    },
                                    {
                                      xtype      : 'numberfield',
                                      fieldLabel : 'Deal Size<font color=red>*</font>',
                                      id         : 'dealSize',
                                      //name       : 'dealSize',
                                      //allowBlank : false,
                                      width      :  130
                                      
                                    },
					                {
                                        xtype     : 'compositefield',
                                        fieldLabel: 'Closing Probability',
                                        items     : [
														{
															xtype        : 'combo',
														    //fieldLabel   : 'Closing Probability',
														    id	         : 'oppClosingProbability',
														    valueField   : 'id',
														    value        :'SELECT',
															store        : confidencelevelStore,
															displayField : 'name',
															triggerAction: 'all',
															value        : 'SELECT',
															typeAhead    : false,
															editable     : false,
															width        : 130,
														    listeners	: {select : function(){
														    						bindValue('oppClosingProbability', 'oppClosingProbabilityId');
														    					} 
														    			  }
														},
														{
															xtype		: 'hidden',
															id			: 'oppClosingProbabilityId'
														}
                                                     ]
					                },
					                {
                                        xtype     : 'compositefield',
                                        fieldLabel: 'Sales Person',
                                        items     : [
                                                       {
													    xtype        : 'combo',
													    //fieldLabel   : 'Sales Person',
													    id           : 'salesPerson',
													    valueField   : 'id',
													    value        :'SELECT',
													    store        : salespersonStore,
													    displayField : 'name',
													    triggerAction: 'all',
													    value        : 'SELECT',
													    typeAhead    : false,
													    editable     : false,
													    width        : 130,
													    listeners	: {select : function(){
													        						bindValue('salesPerson', 'salesPersonId');
													        					} 
													        			  }
													    },
													    {
													    	xtype		: 'hidden',
													    	id			: 'salesPersonId'
													    }
                                                     ]
					                },
                                    {
                                        xtype     : 'compositefield',
                                        fieldLabel: 'Stage',
                                        items     : [
                                                     {
                                                         xtype        : 'combo',
                                                         id           : 'stage',
                                                         //hiddenName   : 'stageHiddenName',
                                                         valueField   : 'id',
                                                         value        :'SELECT',
                                                         store        : stageStore,
                                                         displayField : 'name',
                                                         triggerAction:'all',
                                                         value        : 'SELECT',
                                                         typeAhead    : false,
                                                         editable     : false,
                                                         width        : 130,
                                                         listeners	: {select : function(){
										                    						bindValue('stage', 'stageId');
										                    					} 
										                    			  }
										                },
										                {
										                	xtype		: 'hidden',
										                	id			: 'stageId'
										                },
                                                      {  xtype    :'displayfield',value : 'Create Date:'},
                                                      {
                                                         xtype    : 'datefield',
                                                         id       : 'createDate',
                                                         name     : 'createDate',
                                                        // vtype    : 'daterange',
                                                         endDateField: 'targetDate',
                                                         format   : 'Y-m-d',
                                                         width    : 120
                                                      }
                                                    ]
                                    },
                                    {
                                        xtype     : 'compositefield',
                                        fieldLabel: 'Status',
                                        items     : [
                                                     {
                                                         xtype        : 'combo',
                                                         id           : 'status',
                                                         //hiddenName   : 'statusHiddenName',
                                                         store        : statusStore,
                                                         displayField : 'name',
                                                         valueField   : 'id',
                                                         value        :'SELECT',
                                                         triggerAction: 'all',
                                                         value        : 'SELECT',
                                                         typeAhead    : false,
                                                         editable     : false,
                                                         width    	  : 130,
                                                         listeners	: {select : function(){
									                    						bindValue('status', 'statusId');
									                    					} 
									                    			  }
									                },
									                {
									                	xtype		: 'hidden',
									                	id			: 'statusId'
									                },
                                                      {
                                                         xtype : 'displayfield',
                                                         value : 'Target Date:'
                                                      },
                                                      {
                                                         xtype : 'datefield',
                                                         id    : 'targetDate',
                                                         //name  : 'targetDate',
                                                         format: 'Y-m-d',
                                                         //vtype : 'daterange',
                                                         startDateField: 'createDate',
                                                         width : 120
                                                      }
                                                    ]
                                    },
                                    {
                                      xtype      : 'datefield',
                                      fieldLabel : 'Actual Close Date',
                                      id         : 'actualCloseDate',
                                      //name       : 'actualCloseDate',
                                      format     : 'Y-m-d',
                                      width      : 130
                                    },
                                    {
                                      xtype      : 'textfield',
                                      fieldLabel : 'Description',
                                      id         : 'opportunityDiscription',
                                      //name       : 'opportunityDiscription',
                                      width      : 330
                                    }
                                  ]
                };

                var associatedPanel = {
                    xtype       : 'fieldset',
                    id          : 'associatedPanel',
                    title       : 'Associated With',
                    width       : 520,
                    height      : 300,
                    layout      : 'form',
                    labelWidth  : 120,
                    items       : [
									{
									    xtype   : 'hidden',
									    id      : 'id'
									 },
                                    {
                                      xtype     : 'compositefield',
                                      fieldLabel: 'Name',
                                      items     : [
                                                    
                                                    {
                                                        xtype   : 'textfield',
                                                        id      : 'firstName',
                                                        width   :  240,
                                                        disabled: true
                                                        //allowBlank:false
                                                     },
                                                     {
                                                       xtype  : 'button',
                                                       text   : 'Search Lead',
                                                       cls    : 'searchBtn',
                                                       handler: function(){
															showLeadSearchWindow();
															
														}
                                                     }
                                                   ]
                                    },
                                    {
                                      xtype      : 'textfield',
                                      fieldLabel : 'Company Name',
                                      id         : 'companyName',
                                      width      : 320,
                                      disabled   : true 
                                    },
                                    {
                                      xtype      : 'textfield',
                                      fieldLabel : 'Title',
                                      id         : 'title',
                                      disabled   : true,
                                      width      : 320
                                    },
                                    {
                                        xtype       : 'compositefield',
                                        fieldLabel  : 'Phone(Work)',
                                        items       : [
                                                       {
                                                           xtype    : 'textfield',
                                                           id       : 'phone1',
                                                           //name     : 'phone1',
                                                           width    : 115,
                                                           disabled : true
                                                           
                                                       },
                                                       {xtype:'displayfield', value: 'Phone (Mobile)'},
                                                       {
                                                           xtype    : 'textfield',
                                                           id       : 'phone2',
                                                          // name     : 'phone2',
                                                           width    : 118,
                                                           disabled : true
                                                           
                                                       }
                                                      ]
                                    },
                                    {
                                      xtype      : 'textfield',
                                      fieldLabel : 'Email Id',
                                      id         : 'email',
                                     // name       : 'email',
                                      width      : 320,
                                      disabled   : true
                                    }
                                  ]
                };

               
                
                var opportunityRootPanel ={
                    xtype       : 'panel',
                    id          : 'opportunityRootPanel',
                    width       : 1070,
                    autoHeight  : true,
                    frame       : true,
                    items       : [
                                   {
                                       xtype   : 'panel',
                                       layout  : 'hbox',
                                       items   : [opportunityPanel, associatedPanel]
                                   }
                                 ],
                   tbar        : {
			                        xtype       : 'toolbar',
			                        buttonAlign : 'right',
			                        items       : [
			   			                           {
				                                        xtype  : 'button',
				                                        text   : 'Clear',
				                                        id     : 'topNewButton',
				                                        handler: newOpportunityForm
				                                     },'-',
				                                     {
				                                        xtype  : 'button',
				                                        text   : 'Edit',
				                                        id     : 'topEditButton',
				                                        handler: function(){editOpportunityForm();}
				                                     },'-',
				                                     {
				                                      xtype   : 'button',
				                                      text    : 'Save',
				                                      id      : 'topSaveButton',
				                                      handler : function(){//addOpportunity(mainPanel);
				                                    	 				validateAndSaveOpportunity(mainPanel);
				                                    	 			}
				                                      },
			                                          '-',
			                                          {
				                                          xtype   : 'button',
				                                          id	  : 'topRemoveButton',
				                                          text    : 'Remove'
				                                          //,handler : validateAndSaveOpportunity
				                                       }
				                                     ]
			                      },
                   
                    bbar        : {
                                    xtype       : 'toolbar',
                                    buttonAlign : 'right',
                                    items       : [
													
                                                   {
                                                      xtype  : 'button',
                                                      text   : 'Clear',
                                                      id     : 'newButton',
                                                      handler: newOpportunityForm
                                                   },'-',
                                                   {
                                                      xtype  : 'button',
                                                      text   : 'Edit',
                                                      id     : 'editButton',
                                                      handler: function(){editOpportunityForm();}
                                                   },'-',
                                                   {
                                                    xtype   : 'button',
                                                    text    : 'Save',
                                                    id      : 'saveButton',
                                                    handler : function(){//addOpportunity(mainPanel);
                                                	   				validateAndSaveOpportunity(mainPanel);
                                                   					}
                                                    //handler : addOpportunity
                                                   },
			                                       '-',
			                                       {
				                                    xtype   : 'button',
				                                    id	  	: 'removeButton',
				                                    text    : 'Remove'
				                                    //,handler : validateAndSaveOpportunity
				                                    }
                                                ]
                                  }
                };


                var searchTab = {
                		xtype 	: 'panel',
		     	    	id		: 'searchTab',
		     	    	title	: 'Search',
                        height  : 600,
		     	    	items	: [
									CRM.SPComp.createOppSearchComp('opportunitygridId',opportunityStore, CRM.SPComp.createOpportunityColumnModel(), oppSearchCriteriaStore)
		     	    	     	  ]
                };
                
                var detailsTab = {
                		xtype	: 'panel',
		     	    	id		: 'detailsTab',
		     	    	title	: 'Details',
		     	    	items	: [opportunityRootPanel]
                };
                
                var newTab = {
		     	    	xtype	: 'panel',
		     	    	id		: 'newTab',
		     	    	title	: 'New'
                };
                
                var opportunityMainTab = new Ext.TabPanel({
                		xtype	: 'tabpanel',
                		id		: 'opportunityMainTab',
                		activeTab : 0,
                		height	: 650,
                		items	: [searchTab, detailsTab]
                });
                
               
                
                var mainPanel = new Ext.FormPanel({
                    //renderTo    : Ext.getBody(),
                    id          : 'mainPanel',
                    height      : 600,
                    width       : 1350,
                    frame       : false,
                    layout      : 'vbox',
                    items       : [
                                     opportunityMainTab
                                    
                                  ]
                });
                
                validateFormOnLoad(mainPanel, oppCmpIds);
                
                return mainPanel;
		}

			var oppCmpIds = new Array('opportunityTitle','dealSize');
			
			function validateAndSaveOpportunity(form){
	             //var form = Ext.getCmp('mainPanel');
	 			 var validationSuccess = simpleFormValidation(form, oppCmpIds);
	 			 	if(validationSuccess == 'true'){
	 			 		addOpportunity(form);
	 				}
          	 };
          	 
		
           	 
             
            // All function start from here
           function showOpportunityDetails(selectedOpportunityId){
	   	   		var formPanel = Ext.getCmp('mainPanel');
					formPanel.getForm().load({
					method  : 'GET',
		            url     : 'opportunity/showOpportunityDetails?opportunityId='+selectedOpportunityId,
		      		success : function() {
		      					disableOpportunityForm();
		            			},
		            failure:function() { 
		                		alert ("Failure");
		               			}
					});
					Ext.getCmp('opportunityMainTab').setActiveTab('detailsTab');
			};
               
        	            	    
        	var win;
        	function closeSearchWindow(){
        		win.close();
        	};
        	
        	function showLeadSearchWindow(){
        		var leadStore=CRM.commons.createStore('leadStoreid',CRM.SPComp.leadDataArray,'searchleads/showLeads');
        		var leadSearchCriteriaStore=CRM.commons.createComboStore('leadSearchCriteriaStoreid', 'opportunity/leadSearchCriteriaTypes');
        		
    			var searchLeadPanel = CRM.SPComp.createSearchComp('spSearchLeadGridPanel', 'searchCriteria', 'criteriaValue', leadStore, CRM.SPComp.createLeadColumnModel(), leadSearchCriteriaStore)
     			var searchLeadGrid = new Ext.getCmp('spSearchLeadGridPanel');
    			searchLeadGrid.getColumnModel().setHidden(12,true);
    			
    			win = new Ext.Window({
            	title		: 'Dynamic Search Window',
            	id			: 'searchWindow',
            	width		: 1170,
            	height		: 490,
            	border		: true,
            	plain		: false,
            	closable	: true,
            	collapsible : true,
            	animCollapse: true,
            	draggable 	: true,
            	maximizable : false,
            	//layout		: 'border',
            	onEsc		: true,
            	model		: true,
            	items		: [
								searchLeadPanel
            	     		  ],
            	bbar        : {
    			                    xtype       : 'toolbar',
    			                    buttonAlign : 'right',
    			                    items       : [
    			                        {
    			                            xtype   : 'button',
    			                            text    : 'OK',
    			                            handler : function(){
		    			                        	var record = Ext.getCmp('spSearchLeadGridPanel').getSelectionModel().getSelected();
		    			                        	var form = Ext.getCmp('mainPanel');
		    			                        	form.getForm().loadRecord(record);
			                            	        closeSearchWindow();
    			                            		}
    			                        }
    			                    ]
    			                }     		  
     			
        		});
     			
            win.show(this);
            return win;
            
    	 } 

                    
            //Function for edit ,update ,delete button
            
        	function addOpportunity(formPanel) {
               var action = Ext.getCmp('saveButton').getText();
               var message = 'No action taken.';
                if(action == 'Save'){
             	   message = 'Saved Successfully!';
                }
                if(action == 'Update'){
             	   message = 'Updated Successfully!';
                }
            	var values = formPanel.getForm().getValues();
    	        var data = Ext.encode(values);
    	        Ext.Ajax.request({
          		   url		: 'opportunity/save?action='+action,
          		   method	: 'POST',
          		   success	: function(result, request){
          			  			var jsonData = Ext.util.JSON.decode(result.responseText); 
          			  			var responsedOpportunityId = jsonData.data;
          			   			alert("Opportunity"+message);
          			   			disableOpportunityForm(formPanel);
          			   			Ext.getCmp('opportunityId').setValue(responsedOpportunityId);
          			   		  },
          		   failure 	: function(){
          			   			alert("failure");
          			   		  },
          		   jsonData : data   
    	        });
    	    };

    	   
    	    function disableOpportunityForm(formPanel){
    	    	
    	        //doFormReadOnly(formPanel, oppFormIds, true);
    	    	Ext.getCmp('opportunityTitle').disable();
				Ext.getCmp('dealSize').disable();
				Ext.getCmp('oppClosingProbability').disable();
				Ext.getCmp('salesPerson').disable();
				Ext.getCmp('stage').disable();
				Ext.getCmp('targetDate').disable();
				Ext.getCmp('status').disable();
				Ext.getCmp('createDate').disable();
				Ext.getCmp('actualCloseDate').disable();
				Ext.getCmp('opportunityDiscription').disable();
    	        
    	    	Ext.getCmp('saveButton').disable();
				Ext.getCmp('topSaveButton').disable();
				
				Ext.getCmp('editButton').enable();
				Ext.getCmp('topEditButton').enable();
				//applyOpportunityAuthorization(); //this method is in NewHeader.js
    	    };

    	    function editOpportunityForm(){
    	    	//var oppForm = Ext.getCmp('mainPanel'); 
    	    	//doFormReadOnly(oppForm, oppFormIds, false);
    	  
    	    	Ext.getCmp('opportunityTitle').enable();
				Ext.getCmp('dealSize').enable();
				Ext.getCmp('oppClosingProbability').enable();
				Ext.getCmp('salesPerson').enable();
				Ext.getCmp('stage').enable();
				Ext.getCmp('targetDate').enable();
				Ext.getCmp('status').enable();
				Ext.getCmp('createDate').enable();
				Ext.getCmp('actualCloseDate').enable();
				Ext.getCmp('opportunityDiscription').enable();
    	    	
    	        Ext.getCmp('saveButton').enable();
				Ext.getCmp('topSaveButton').enable();
				Ext.getCmp('saveButton').setText('Update');	
				Ext.getCmp('topSaveButton').setText('Update');
    	    };

    	    function newOpportunityForm(){
				editOpportunityForm();
				//var oppForm = Ext.getCmp('mainPanel'); 
				//oppForm.getForm().reset();
    	    	Ext.getCmp('opportunityTitle').setValue(null);
				Ext.getCmp('dealSize').setValue(null);
				Ext.getCmp('oppClosingProbability').setValue(null);
				Ext.getCmp('salesPerson').setValue(null);
				Ext.getCmp('stage').setValue(null);
				Ext.getCmp('targetDate').setValue(null);
				Ext.getCmp('status').setValue(null);
				Ext.getCmp('createDate').setValue(null);
				Ext.getCmp('actualCloseDate').setValue(null);
				Ext.getCmp('opportunityDiscription').setValue(null);
				//Ext.getCmp('leadId').setValue();
				Ext.getCmp('firstName').setValue(null);
				Ext.getCmp('companyName').setValue(null);
				Ext.getCmp('title').setValue(null);
				Ext.getCmp('phone1').setValue(null);
				Ext.getCmp('phone2').setValue(null);
				Ext.getCmp('email').setValue(null);
				
    	    	
				Ext.getCmp('saveButton').setText('Save');
				Ext.getCmp('topSaveButton').setText('Save');
				Ext.getCmp('saveButton').enable();
				Ext.getCmp('topSaveButton').enable();						
				Ext.getCmp('editButton').disable();
				Ext.getCmp('topEditButton').disable();
				//applyOpportunityAuthorization(); // this method is in NewHeader.js
		};

    	   //function for delete records from grid
    	   
    	   function showOpportunityList(){
				var grid = Ext.getCmp('opportunitygridId');
				grid.store.removeAll();
				grid.store.reload();
		   }

    	   function deleteOppDetails(){
	  			var record = Ext.getCmp('opportunitygridId').getSelectionModel().getSelected();
	    		var selectedOppId = record.get('id');
	    		Ext.Ajax.request({
	   			method  : 'POST',
	   	        url     :  'opportunity/deleteOpportunityDetail?opportunityId='+selectedOppId,
	   	      		success : function() {
	   				           showOpportunityList();
	   	            			},
	   	            failure:function() { 
	   	                		alert('Failure!');
	   	               			}
	   			});
   			}

   		function showOppMessage(){
   			 Ext.MessageBox.show({
         	            title	: 'Confirm',
         	            msg		: 'Are you sure you want to delete this records:',
         	            width	:200,
         	            buttons	: Ext.MessageBox.OKCANCEL,
         	            multiline: false,
         	            fn		: function(btn, text) {
		         	            	if (btn == 'ok') {
		         	            		deleteOppDetails();
		         	            	   }
		         	            	}
         	           });
   				}
  